package com.yami.shop.delivery.api.listener;

import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.vo.ProductVO;
import com.yami.shop.bean.event.CheckAddrEvent;
import com.yami.shop.bean.model.Area;
import com.yami.shop.bean.model.UserAddr;
import com.yami.shop.delivery.common.model.Transfee;
import com.yami.shop.delivery.common.model.Transport;
import com.yami.shop.delivery.common.service.TransportService;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.UserAddrService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component("checkAddrListener")
@AllArgsConstructor
public class CheckAddrListener {

    private final DeliveryService deliveryService;
    private final TransportService transportService;

    private final UserAddrService userAddrService;

    /**
     * 判断用户默认地址是否超出配送区域
     *
     * @param event
     */
    @EventListener(CheckAddrEvent.class)
    public void checkAddrListenerEvent(CheckAddrEvent event) {
        String userId = event.getUserId();
        Long addrId = event.getAddrId();
        if (!Objects.isNull(event.getShopCartItemDto())) {
            ShopCartItemDto shopCartItemDto = event.getShopCartItemDto();
            shopCartItemDto.setIsDelivery(check(shopCartItemDto.getDeliveryTemplateId(), userId, addrId));
        }else{
            ProductVO productVO = event.getProductVO();
            productVO.setIsDelivery(check(productVO.getDeliveryTemplateId(), userId, addrId));
        }
    }

    private Boolean check(Long deliveryTemplateId, String userId, Long addrId) {
        if (Objects.isNull(userId) || deliveryTemplateId == 0 || deliveryTemplateId == -1) {
            return true;
        }
        Transport transprot = transportService.getTransportAndAllItems(deliveryTemplateId);
        UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId);
        if (Objects.isNull(userAddr) || transprot.getIsFreeFee() == 1) {
            return true;
        }
        List<Area> areaList = new ArrayList<>();
        List<Transfee> transFees = transprot.getTransfees();
        if (!transFees.isEmpty()) {
            for (Transfee transFee : transFees) {
                areaList.addAll(transFee.getCityList());
            }
        }
        Map<Long, List<Area>> areaMap = areaList.stream().collect(Collectors.groupingBy(Area::getAreaId));
        if (areaMap.containsKey(userAddr.getAreaId())) {
            return true;
        } else {
            return false;
        }
    }
}
